import axios from "axios";

import { ElMessage, ElMessageBox } from "element-plus";

import { showLoading, hideLoading } from "@/utils/loading";

// var baseurl = 'https://zyk.icve.com.cn/'

const instance = axios.create({
  withCredentials: true, // 表示请求可以携带cookie
  timeout: 5000,
});

instance.interceptors.request.use(
  (config) => {
    // 请求拦截进来调用显示loading效果
    // showLoading()
    config.baseURL =
      config.baseURL ||
      (process.env.NODE_ENV === "development" ? "/apis" : "/");

      if(config.url.includes('knowledge')){
        // console.log(123)
        // console.log(config.url)
        // config.headers['Content-Type'] = 'application/json, text/plain, */*'
      }
    // 断网提示
    if (!navigator.onLine) {
      ElMessageBox.alert("您的网络故障，请检查!", "温馨提示", {
        confirmButtonText: "好的",
        type: "warning",
      });
    }

    // 判断是否存在token，如果存在将每个页面header都添加token
    // if (getToken()) {
    //   config.headers.Authorization = getToken()
    // }
    return config;
  },
  (error) => {
    console.log("请求拦截error", error);
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    setTimeout(() => {
      hideLoading();
    }, 200);
    const { data, config } = response;
    const { code, msg } = data;
    // 操作正常Code数组
    const codeVerificationArray = [...[1]];
    // 是否操作正常
    if (codeVerificationArray.includes(code)) {
      return data;
    } else {
      return data;
      // return Promise.reject(
      //   "请求异常拦截:" + JSON.stringify({ url: config.url, code, msg }) ||
      //     "Error"
      // );
    }
  },
  (error) => {
    if (error.response && error.response.data) {
      return Promise.reject(error);
    } else {
      let { message } = error;
      if (message === "Network Error") {
        message = "后端接口连接异常";
      }
      if (message.includes("timeout")) {
        message = "后端接口请求超时";
      }
      if (message.includes("Request failed with status code")) {
        const code = message.substr(message.length - 3);
        message = "后端接口" + code + "异常";
      }
      return Promise.reject(error);
    }
  }
);

export default instance;
